/*
 *BASE_URL
 */
const BASE_URL = 'https://ynf.xxhf.cn/index.php'

export const API = (options) => {
	return new Promise((resolve, reject) => { // 异步处理的封装通过promise比较好，并且要return出去，
		uni.showLoading({
			title: '加载中...',
			mask: true
		});
		let ContentType = 'application/json; charset=UTF-8'
		if (options.url === '/api/user/leshua_register' || options.url === '/api/user/leshua_register1'
		|| options.url === '/api/user/save_user_rate' || options.url === '/api/user/leshua_update') {
			ContentType = 'application/x-www-form-urlencoded'
		}
		if (!uni.getStorageSync('token') && options.url !== '/api/user/login') {
			uni.showToast({
				title: '请登录后操作',
				icon: 'none',
				duration: 1500,
				success: (res)=> {
					setTimeout(()=>{
						uni.reLaunch({
							url: '/pages/user/login'
						});
					},1000)
				}
			});
			return
		}
		uni.request({
			url: BASE_URL + options.url,
			method: options.method || 'GET',
			data: options.data || {},
			header: {
				'token': uni.getStorageSync('token') || '',
				"Content-Type": ContentType
			},
			success: (res) => {
				if (res.data.code === 401) {
					uni.showToast({
						title: '请登录后操作',
						icon: 'none',
						duration: 2000,
						success: (res)=> {
							setTimeout(()=>{
								uni.redirectTo({
									url:'/pages/user/login'
								});
							},1500)
						}
					});
					return
				}
				if (res.data.code === 1 || options.url === '/api/user/get_les_merchant' || options.url === '/api/user/leshua_register1') {
					resolve(res.data)
				} else {
					uni.showToast({
						title: res.data.msg || '暂无数据',
						icon: 'none',
						duration: 2000,
						success: (res)=> {
							
						}
					});
				}
				// resolve(res.data)
			},
			fail: (err) => {
				uni.showToast({ // 给一个消息提示
					icon: 'error',
					title: '请求接口失败！'
				})
				reject(err) // 调用reject方法把错误消息返回出去
			},
			complete: (e) => {
				uni.hideLoading();
			}

		})
	})
}
